package com.geekhalo.domainevent.v4;

import com.geekhalo.domainevent.service.*;
import com.google.common.base.Preconditions;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
public class RocketMQEvent implements OrderService{
    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    @Transactional
    public void createOrder(CreateOrderCommand createOrderCommand) {

        // 1. 处理订单逻辑
        Preconditions.checkArgument(createOrderCommand.isValid());

        Order order = Order.create(createOrderCommand);

        this.orderRepository.save(order);

        Message<Order> message = MessageBuilder
                .withPayload(order)
                .build();
        this.rocketMQTemplate.syncSend("order-service-topic", message);
    }
}
